<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '服务列表',
  },
}
</route>
<template>
  <view class="service-listing-page min-h-screen bg-gray-50">
    <view class="bg-gradient-to-b from-orange-500 pt-header to-white pb-16 px-2">
      <view class="text-2xl font-bold text-white text-center">服务列表</view>
    </view>

    <!-- Service Types Section -->
    <view class="px-2 -mt-10" v-if="categoryList.length > 0">
      <view class="bg-white rounded-lg shadow-lg p-2">
        <view class="service-types-container overflow-x-auto">
          <view class="flex justify-around space-x-4 pb-2">
            <view v-for="category in categoryList" :key="category.id"
              class="flex flex-col items-center flex-shrink-0 cursor-pointer"
              :class="cateId == category.id ? 'text-orange-500' : 'text-gray-600'" @click="setCateId(category.id)">
              <view class="w-14 h-14 rounded-full flex items-center justify-center mb-1"
                :class="cateId == category.id ? 'bg-orange-100' : 'bg-gray-100'">
                <image :src="category.image" :alt="category.cateName" class="w-8 h-8" />
              </view>
              <text class="text-xs">{{ category.cateName }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="px-2 pb-20" :class="{ 'mt-4': categoryList.length > 0 }">
      <view class="bg-white rounded-lg shadow-lg p-2 mb-4">
        <view class="flex justify-between">
          <view v-for="(option, index) in sortOptions" :key="index" class="px-3 py-1 text-sm rounded-full" :class="activeSortOption === index ? 'bg-orange-500 text-white' : 'bg-gray-100 text-gray-700'
            " @click="setActiveSortOption(option, index)">
            {{ option.label }}
          </view>
        </view>
      </view>

      <view class="space-y-4">
        <wd-status-tip image="search" v-if="productList.length === 0" tip="当前搜索无结果" />

        <view v-for="service in productList" :key="service.id" class="bg-white rounded-lg shadow p-2"
          @click="openServiceModal(service)">
          <view class="flex">
            <image :src="service.image" :alt="service.name" class="w-24 h-24 rounded-lg object-cover mr-4" />
            <view class="flex-1">
              <view class="flex justify-between items-start">
                <view class="font-bold text-gray-800">{{ service.name }}</view>
                <text class="text-xs px-2 py-1 bg-orange-100 text-orange-600 rounded">
                  {{ service.storeName }}
                </text>
              </view>

              <view class="flex items-center mt-1 text-xs text-gray-500">
                <text>销量 {{ service.sales }}</text>
              </view>

              <view class="flex justify-between items-end mt-2">
                <view class="flex items-baseline" v-if="service.vipPrice == 0">
                  <text class="text-orange-500">立即预约</text>
                </view>
                <view class="flex items-baseline" v-else>
                  <text class="text-xs text-orange-500 mr-0.5">¥</text>
                  <text class="text-lg font-bold text-orange-500">{{ service.vipPrice }}</text>
                  <text class="text-xs text-gray-500 ml-1">起</text>
                </view>
                <!-- <view class="text-xs text-gray-500">距离 {{ service.distance }}km</view> -->
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- Loading Modal -->
    <view v-if="isLoading" class="fixed inset-0 bg-black/30 flex items-center justify-center z-30">
      <view class="bg-white rounded-lg p-6 flex flex-col items-center">
        <view class="w-12 h-12 border-4 border-orange-500 border-t-transparent rounded-full animate-spin mb-4"></view>
        <view class="text-gray-700">加载中...</view>
      </view>
    </view>

    <!-- Service Detail Modal -->
    <view v-if="showServiceModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-40 px-2"
      @click="showServiceModal = false">
      <view class="bg-white rounded-lg w-full max-w-md max-h-[90vh] overflow-y-auto" @click.stop>
        <view class="relative p-5">
          <view class="absolute top-4 right-4 text-gray-500 hover:text-gray-700" @click="showServiceModal = false">
            <X class="w-5 h-5" />
          </view>

          <view class="text-xl font-bold text-gray-800 mb-4">{{ selectedService.storeName }}</view>
          <view class="text-xl font-bold text-gray-800 mb-4">{{ selectedService.name }}</view>

          <view class="mb-6">
            <image :src="selectedService.image" :alt="selectedService.name"
              class="w-full h-48 object-cover rounded-lg mb-3" />

            <view class="flex justify-between items-center">
              <view class="flex items-baseline" v-if="selectedService.vipPrice > 0">
                <text class="text-xs text-orange-500 mr-0.5">¥</text>
                <text class="text-2xl font-bold text-orange-500">
                  {{ selectedService.vipPrice }}
                </text>
                <text class="text-xs text-gray-500 ml-1">起</text>
              </view>

              <view class="flex items-baseline" v-else>
                <text class="font-bold text-orange-500">立即预约</text>
              </view>

              <view class="flex items-center">
                <Star class="w-4 h-4 text-orange-500 mr-1" />
                <text class="font-medium">{{ selectedService.rating }}</text>
                <text class="text-gray-500 text-sm ml-2">
                  ({{ selectedService.sales }}人已购买)
                </text>
              </view>
            </view>

            <view class="mt-2 text-sm text-gray-600">
              {{ selectedService.description }}
            </view>
          </view>

          <wd-form ref="form" :model="orderForm">
            <wd-cell-group border>
              <wd-input label="姓名" label-width="100px" prop="name" clearable v-model="orderForm.name"
                placeholder="请输入姓名" :rules="[{ required: true, message: '请填写姓名' }]" />

              <wd-input label="手机号" label-width="100px" prop="phone" clearable v-model="orderForm.phone"
                placeholder="请输入手机号" :rules="[{ required: true, message: '请填写手机号' }]" />

              <wd-textarea label="详细地址" label-width="100px" prop="detailedAddress" :auto-height="true" clearable
                v-model="orderForm.detailedAddress" placeholder="请输入详细地址"
                :rules="[{ required: true, message: '请填写详细地址' }]" />

              <wd-datetime-picker label="上门时间" label-width="100px" prop="upperTime" placeholder="请输入上门时间"
                v-model="orderForm.upperTime" :rules="[{ required: true, message: '请填写上门时间' }]" />
            </wd-cell-group>

            <view class="footer">
              <wd-button type="primary" size="large" @click="submitOrder" block>提交</wd-button>
            </view>
          </wd-form>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Star, X } from 'lucide-vue-next'
import { http } from '@/utils/http'
import dayjs from 'dayjs'

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  type: '',
  sequence: 2,
})

const categoryList = ref([])
const cateId = ref(0)
const activeSortOption = ref(0)
const productList = ref([])
const isLoading = ref(false)

const getCategoryList = async () => {
  let res = await http.get('/api/home/categories', {
    pid: 0,
    type: 1,
  })
  if (res.code == 200) {
    categoryList.value = res.data.categories

    categoryList.value.unshift({
      id: '',
      cateName: '全部',
      image: 'http://llcdn.jxsr.com/917d0304-b766-4c50-9fe2-1ab43d524bb7能.png',
    })

    queryParams.pageNum = 1
    getProductList()
  }
}

const total = ref(0)

const getProductList = async () => {
  let res = await http.get('/api/home/products', {
    ...queryParams.value,
    cateId: cateId.value,
    type: 1,
  })
  if (res.code == 200) {
    total.value = res.data.total

    console.log('res', res)
    if (queryParams.value.pageNum == 1) {
      productList.value = res.data.products
    } else {
      productList.value = productList.value.concat(res.data.products)
    }
  }
}

const setCateId = (id) => {
  if (cateId.value != id) {
    cateId.value = id

    queryParams.value.type = ''
    queryParams.value.sequence = 'desc'
    queryParams.value.pageNum = 1

    getProductList()
  }
}

// Sort Options
const sortOptions = [
  {
    label: '默认排序',
    type1: '',
    sequence: 'desc',
  },
  {
    label: '销量优先',
    type1: '1',
    sequence: 'desc',
  },
  {
    label: '价格优先',
    type1: '2',
    sequence: 'desc',
  },
  // { label: '距离优先', type1: '', sequence: 'desc' },
]

const setActiveSortOption = (option, index) => {
  if (activeSortOption.value == index) {
    return
  }

  activeSortOption.value = index
  queryParams.value.type1 = option.type1
  queryParams.value.sequence = option.sequence
  queryParams.value.pageNum = 1
  getProductList()
}

const loadMore = async () => {
  isLoading.value = true
  try {
    queryParams.value.pageNum = queryParams.value.pageNum + 1
    await getProductList()
  } catch (error) {
    console.log('error', error)
  } finally {
    isLoading.value = false
  }
}

onReachBottom(() => {
  if (total.value > productList.value.length) {
    loadMore()
  } else {
    uni.showToast({
      title: '没有更多了',
      icon: 'none',
      mask: false,
    })
  }
})

// Service Detail Modal
const showServiceModal = ref(false)
const selectedService = ref({})
const isSubmitting = ref(false)

const orderForm = ref({
  content: '',
  images: '',
  name: '',
  phone: '',
  detailedAddress: '',
  upperTime: '',
})

const openServiceModal = (service) => {
  uni.navigateTo({ url: '/pages/product/detail?scene=' + service.id })

  return

  console.log('%c [ service ]-355', 'font-size:13px; background:pink; color:#bf2c9f;', service)
  selectedService.value = service
  showServiceModal.value = true

  orderForm.value = {
    id: service.id,
    content: '',
    images: '',
    name: '',
    phone: '',
    detailedAddress: '',
    upperTime: dayjs().add(3, 'hour').startOf('hour').format('YYYY-MM-DD HH:mm:ss'),
  }
}

const submitOrder = async () => {
  isSubmitting.value = true
  // 提交
  try {
    // let res = await http.post('/api/reservation/userReservation', orderForm.value)
    // if (res.code == 200) {
    //   console.log('res', res)
    //   getProductList()
    // }

    let data = {
      number: 1,
      remark: '',
      orderType: 3,
      groupId: 0,
      couponId: 0,
      ...orderForm.value,
    }

    console.log('data', data)

    let res = await http({
      url: '/api/wxPayApplet/productWxPay',
      method: 'POST',
      data: data,
    })

    if (res.code == 200) {
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: 'MD5',
        paySign: res.data.paySign,
        success: (res) => {
          uni.showToast({
            title: '支付成功',
            icon: 'success',
          })
        },
        fail: (err) => {
          uni.showToast({
            title: '支付失败',
            icon: 'none',
          })
        },
      })
    }
  } catch (error) {
    console.log('error', error)
  } finally {
    showServiceModal.value = false
    isSubmitting.value = false
  }
}

onLoad((option) => {
  cateId.value = option.cateId
  getCategoryList()
})

onShareAppMessage(() => {
  return {
    title: '邻里生活荟',
    path: '/pages/serviceList/index?cateId=' + cateId.value,
  }
})
onShareTimeline(() => {
  return {
    title: '邻里生活荟',
    path: '/pages/serviceList/index?cateId=' + cateId.value,
  }
})
</script>

<style scoped>
.service-types-container {
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE and Edge */
}

.service-types-container::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari, Opera */
}
</style>
